package net.crashtoot.picasa.web.rest;

import java.util.ArrayList;
import java.util.List;

import net.crashtoot.picasa.core.model.Account;
import net.crashtoot.picasa.core.model.User;
import net.crashtoot.picasa.core.service.AccountService;
import net.crashtoot.picasa.core.service.PhotoService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Log log = LogFactory.getLog(UserController.class);

    @Autowired
    private AccountService accountService;

    @Autowired
    private PhotoService photoService;

    /**
     * @return tous les utilisateurs.
     * @throws Exception
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<User> listUsers() throws Exception {
        List<Account> accounts = accountService.listAll();

        if (accounts == null || accounts.size() == 0) {
            return null;
        }

        List<User> users = new ArrayList<User>();
        for (Account account : accounts) {
            users.add(photoService.getUser(account));
        }
        log.info(users.size() + " utilisateurs");

        return users;
    }

    @RequestMapping(value = "/{userId:.*}/")
    public User getUser(@PathVariable String userId) throws Exception {
        Account account = accountService.getAccountByUserName(userId);
        if (account == null) {
            return null;
        }
        return photoService.getUser(account);
    }
}
